import { login } from '@/api/u/login'
import { getUserInfo } from '@/api/u/user'

const getDefaultState = () => {
  return {
    user: {},
    token: '',
    msgCount:0
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_USER: (state, user) => {
    state.user = user
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_MSG: (state, count) => {
    state.msgCount = count
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        const { code, data} = response
        if (code === 200) {
          commit('SET_TOKEN', data)
          localStorage.setItem('token', data)
          resolve()
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit,dispatch }) {
    const token = localStorage.getItem('token')
    commit('SET_TOKEN', token)
    return new Promise((resolve, reject) => {
      getUserInfo().then(response => {
        const { code, data} = response
        if (code !== 200) {
          dispatch("dialog/setlogin", true,{root: true});
          return reject('用户未认证，请登录！')
        }
        console.log(data)
        commit('SET_USER', data)
        localStorage.setItem('user', JSON.stringify(data))
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  getMsg({ commit }) {
    console.log("获取消息")
    commit('SET_MSG', "")
    // return new Promise((resolve, reject) => {
    //   eduApi.getMsgByList(1).then(response => {
    //     const { code, data} = response
    //     if (code !== 20000) {
    //       return reject('用户未认证，请登录！')
    //     }
    //     commit('SET_MSG', data.unread)
    //     resolve(data)
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },
  // user logout
  logout({ commit }) {
    console.log("退出登录");
    return new Promise((resolve) => {
      localStorage.removeItem('token');
      commit('RESET_STATE');
      resolve()
      // logout().then(() => {
      //   // removeToken() // must remove  token  first
      //   localStorage.removeItem('token')
      //   // store.dispatch('resetRouters')
      //   // resetRouter()
      //   commit('RESET_STATE')
      //   // location.reload()
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },
  setInfo({ commit }, userInfo) {
    commit('SET_USER', userInfo)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

